package com.wanban.adutils.advertisers.ironsource

import android.app.Activity
import android.text.TextUtils
import android.util.Log
import com.ironsource.mediationsdk.IronSource
import com.unity3d.mediation.LevelPlayAdError
import com.unity3d.mediation.LevelPlayAdInfo
import com.unity3d.mediation.rewarded.LevelPlayReward
import com.unity3d.mediation.rewarded.LevelPlayRewardedAd
import com.unity3d.mediation.rewarded.LevelPlayRewardedAdListener
import com.wanban.adutils.advertisers.BaseAdLoader
import com.wanban.adutils.callback.OnLoadAdCallback
import com.wanban.adutils.db.bean.AdInfo
import com.wanban.adutils.tools.AdConstants


class ISRewardedAdUtils : BaseAdLoader() {

    private var isAdOnceComplete = false
    private var rewardedAd: LevelPlayRewardedAd? = null

    override fun loadAdNew(activity: Activity, adInfo: AdInfo, callback: OnLoadAdCallback) {
        super.loadAdNew(activity, adInfo, callback)
        // 判断广告是否达到请求上线
        if (TextUtils.isEmpty(realUnitId)) {
            // 直接返回奖励
            excSuccessByFail()
            return
        }
        Log.e(AdConstants.TAG, "ISRewardedAdUtils...准备加载广告")
        // 创建广告
        rewardedAd = LevelPlayRewardedAd(adInfo.ad_position)
        // 添加监听，最好在加载广告前设置
        rewardedAd?.setListener(object : LevelPlayRewardedAdListener {

            override fun onAdLoaded(adInfo: LevelPlayAdInfo) {
                if (isAdOnceComplete) return
                isAdOnceComplete = true
                Log.e(AdConstants.TAG, "ISRewardedAdUtils -> onAdAvailable...$isAdOnceComplete")
                activity.runOnUiThread {
                    if (isTimeout) {
                        destroy()
                        return@runOnUiThread
                    }
                    setAdLoadSuccess()
                    sdkLoadFinish()
                    callback.onAdLoaded()
                }
            }

            override fun onAdLoadFailed(error: LevelPlayAdError) {
                if (isAdOnceComplete) return
                Log.e(AdConstants.TAG, "ISRewardedAdUtils -> onAdUnavailable...$isAdOnceComplete")
                activity.runOnUiThread {
                    if (isTimeout) {
                        destroy()
                        return@runOnUiThread
                    }
                    sdkLoadFinish()
                    callback.onAdLoadFailed(AdConstants.ERROR_CODE_NO_FILL)
                    destroy()
                }
            }

            override fun onAdDisplayed(adInfo: LevelPlayAdInfo) {
                isAdOnceComplete = true
                setAdLoadShowing(true)
                activity.runOnUiThread {
                    callback.onAdOpened()
                }
            }

            override fun onAdDisplayFailed(error: LevelPlayAdError, adInfo: LevelPlayAdInfo) {
                super.onAdDisplayFailed(error, adInfo)
                setAdLoadShowing(false)
                isAdOnceComplete = false
                Log.e(AdConstants.TAG, "ISRewardedAdUtils -> onAdShowFailed..." + error.getErrorCode() + ", " + error.getErrorMessage())
                activity.runOnUiThread {
                    val code = error.getErrorCode()
                    callback.onAdLoadFailed(code)
                    destroy()
                }
            }

            override fun onAdClicked(adInfo: LevelPlayAdInfo) {
                super.onAdClicked(adInfo)
                callback.onAdClicked()
            }

            override fun onAdRewarded(reward: LevelPlayReward, adInfo: LevelPlayAdInfo) {
                Log.e(AdConstants.TAG, "ISRewardedAdUtils -> onAdRewarded..." + adInfo.getAdNetwork())
                callback.onUserEarnedReward(10)
            }

            override fun onAdClosed(adInfo: LevelPlayAdInfo) {
                super.onAdClosed(adInfo)
                Log.e(AdConstants.TAG, "ISRewardedAdUtils -> onAdClosed..." + adInfo.getAdNetwork())
                isAdOnceComplete = false
                callback.onAdComplete()
                destroy()
            }
        })

        if (rewardedAd?.isAdReady() == true) {
            Log.e(AdConstants.TAG, "ISRewardedAdUtils -> 有缓存广告，直接返回...")
            isAdOnceComplete = true
            setAdLoadSuccess()
            sdkLoadFinish()
            callback.onAdLoaded()
            return
        }

        rewardedAd?.loadAd()

//        val available = IronSource.isRewardedVideoAvailable()
//        if (available) {
//            Log.e(AdConstants.TAG, "ISRewardedAdUtils -> 有缓存广告，直接返回...")
//            isAdOnceComplete = true
//            setAdLoadSuccess()
//            sdkLoadFinish()
//            callback.onAdLoaded()
//        } else {
//            IronSource.loadRewardedVideo()
//        }
    }



    // 错误当成功返回
    private fun excSuccessByFail(){
        mOnLoadAdCallback?.onUserEarnedReward(10)
        mOnLoadAdCallback?.onAdComplete()
        destroy()
    }

    override fun showAd(activity: Activity) {
        super.showAd(activity)
        if (rewardedAd == null) return
        if (rewardedAd?.isAdReady() == true && !LevelPlayRewardedAd.isPlacementCapped(realUnitId)) {
            rewardedAd?.showAd(activity)
        } else {
            excSuccessByFail()
        }

        // 8.6之前旧Api
//        if (IronSource.isRewardedVideoAvailable()) {
//            IronSource.showRewardedVideo()
//        } else {
//            excSuccessByFail()
//        }
    }

    override fun isAdLoadSuccess(): Boolean {
        return super.isAdLoadSuccess() && rewardedAd?.isAdReady() == true
    }

    override fun destroy() {
        super.destroy()
        rewardedAd = null
//        IronSource.removeRewardedVideoListener()
    }
}